package com.zfast.forge.wechat.controller;

import cn.hutool.http.HttpUtil;
import com.zfast.forge.wechat.config.WxConfig;
import com.zfast.forge.wechat.pojo.bo.JwtUser;
import com.zfast.forge.wechat.service.WxService;
import com.zfast.forge.wechat.utils.JWT;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.hibernate.internal.util.StringHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/wx/auth")
@Api(tags="微信")
public class WxController {

	@Autowired
	WxService wxService;

	int cookie_max_age = 7200*12*365;

	/**
	 * @Description: 待处理
	 * @author zgn
	 * @date 2019年6月17日
	 */
	@RequestMapping("/wxAuth")
	@ApiOperation(value = "微信授权")
	public String wxAuth(HttpServletRequest request, HttpServletResponse response, String storeid, String tableId)
			throws IOException {
		//解码编码 可能需要用户授权unionid
		String code = request.getParameter("code");
		String rawData = request.getParameter("rawData");

		WxConfig wxConfig = new WxConfig(storeid);
		String Code2SessionUri=wxConfig.Code2Session().replace("APPID", wxConfig.getAppId()).replace("SECRET", wxConfig.getAppSecret())
				.replace("JSCODE", code);
		Map urlToMap = URLToMap(Code2SessionUri); //openid,unionid
		if (urlToMap==null||urlToMap.containsKey("errcode")) {
			return "openid未获取！";
		}
		String openid=urlToMap.get("openid").toString();

		wxService.syncWxUserInfo(rawData,openid, wxConfig.getAppId());

		JwtUser jwtUser = new JwtUser();
		jwtUser.setOpenId(openid);
//      System.out.println("unionid============================>" + unionId);
		String memberId = "";//userApiService.checkIsMember(openid);

		if (StringHelper.isNotEmpty(memberId)) {
			jwtUser.setMemberFlag(true);
			jwtUser.setMemberId(memberId);
//          userApiService.login(memberId);
		} else {
			jwtUser.setMemberFlag(false);
		}
		String jwtToken = JWT.sign(jwtUser, 1000 * cookie_max_age);
		// 跳转页面
		boolean isnew=true;
		if (StringHelper.isNotEmpty(memberId)) {
			isnew=false;
		}
		//setJson(JsonResultBuilder.success(true).msg("成功").add("authorization", jwtToken).add("isnew", isnew).json());
		// return JSON;
		return "JSON";
	}

	public Map URLToMap(String uri) throws UnknownHostException {
		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("k1","v1");
		HttpUtil.get(uri,paramMap);
		return null;

		/*String res = HttpUtils.get(uri, "", "utf-8");
		System.out.println("uri=====================" + uri);
		System.out.println("res=====================" + res);
		if (StringUtils.isEmpty(res)) {
			System.out.println("res=====================null" + res);
			return null;
		}
		Map accessInfo = JsonUtils.parse(res, Map.class);
		return accessInfo;*/
	}

	@ApiOperation(value = "微信用户信息", httpMethod = "GET")
	@RequestMapping("/wxUserInfo")
	public String wxUserInfo(HttpServletRequest request, HttpServletResponse response) {
		String token = JWT.getToken(request);
		JwtUser jwtUser = JWT.unsign(token, JwtUser.class);
		String openId = jwtUser.getOpenId();
		//IDtoRow userInfo = wxService.getUserInfoByOpenId(openId);
		//setJson(JsonResultBuilder.success(true).msg("成功").add("userInfo", userInfo).json());
		// return JSON;
		return "JSON";
	}

	@ApiOperation(value = "测试用", httpMethod = "GET")
	@RequestMapping("/test")
	public String test(String memberId) {
		//setJson(JsonResultBuilder.success(true).msg("成功").json());
		// return JSON;
		return "JSON";
	}

}
